package com.example.ecommerce.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.ecommerce.entity.Order;
import com.example.ecommerce.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    public void createOrder(Long userId, String Product_name, Integer quantity, String destination_address,double total_price,int store_id) {
        Order order = new Order();
        order.setUid(userId);
        order.setProductName(Product_name);
        order.setQuantity(quantity);
        order.setDestinationAddress(destination_address);
        order.setOrderTime(LocalDateTime.now());
        order.setState("未发货");
        order.setTotalPrice(total_price);
        order.setStoreId(store_id);


        orderMapper.insert(order);
    }


    public List<Order> getOrdersByUid(Long uid) {
        return orderMapper.selectByUid(uid);  // 你需要在 mapper 中实现这个方法
    }

    public boolean updateOrderIfNotShipped(int orderId, String newAddress, int newQuantity) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !"未发货".equals(order.getState())) {
            return false;
        }
        double unitPrice = (double) order.getTotalPrice() / order.getQuantity();
        order.setDestinationAddress(newAddress);
        order.setQuantity(newQuantity);

        order.setTotalPrice(unitPrice * newQuantity);

        order.setOrderTime(LocalDateTime.now());

        orderMapper.updateById(order);
        return true;
    }


    public boolean returnOrder(int id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return false;
        }

        orderMapper.deleteById(id);
        return true;
    }

    public List<Order> getOrdersByStoreId(int storeId) {
        return orderMapper.selectList(new QueryWrapper<Order>().eq("store_id", storeId));
    }

    public boolean updateOrderState(int orderId, String state) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) return false;

        order.setState(state);
        return orderMapper.updateById(order) == 1;
    }

    public List<Map<String, Object>> getProductSalesStats() {
        List<Order> orders = orderMapper.selectList(null);
        return orders.stream()
                .collect(Collectors.groupingBy(Order::getProductName, Collectors.summingInt(Order::getQuantity)))
                .entrySet().stream()
                .map(e -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("name", e.getKey());
                    m.put("value", e.getValue());
                    return m;
                })
                .collect(Collectors.toList());
    }


    public List<Map<String, Object>> getSellerSalesStats() {
        List<Order> orders = orderMapper.selectList(null);
        return orders.stream()
                .collect(Collectors.groupingBy(Order::getStoreId, Collectors.summingDouble(Order::getTotalPrice)))
                .entrySet().stream()
                .map(e -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("name", "商家ID " + e.getKey());
                    m.put("value", e.getValue());
                    return m;
                })
                .collect(Collectors.toList());
    }

    public List<Map<String, Object>> getUserSpendingStats() {
        List<Order> orders = orderMapper.selectList(null);
        return orders.stream()
                .collect(Collectors.groupingBy(Order::getUid, Collectors.summingDouble(Order::getTotalPrice)))
                .entrySet().stream()
                .map(e -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("name", "用户ID " + e.getKey());
                    m.put("value", e.getValue());
                    return m;
                })
                .collect(Collectors.toList());
    }


    public int deleteByUserId(Long userId) {
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq("uid", userId);
        return orderMapper.delete(query);
    }
}
